package com.jdzcnc.scan.scan

import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.util.TypedValue
import com.journeyapps.barcodescanner.ViewfinderView


class ScanWidget  // This constructor is used when the class is built from an XML resource.
    (context: Context?, attrs: AttributeSet?) : ViewfinderView(context, attrs) {
    /* ******************************************    边角线相关属性    ************************************************/
    /**
     * "边角线长度/扫描边框长度"的占比 (比例越大，线越长)
     */
    var mLineRate = 0.1f

    /**
     * 边角线厚度 (建议使用dp)
     */
    var mLineDepth =
        TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4f, resources.displayMetrics)

    /**
     * 边角线颜色
     */
    var mLineColor: Int = Color.WHITE
    /* *******************************************    扫描线相关属性    ************************************************/
    /**
     * 扫描线起始位置
     */
    var mScanLinePosition = 0

    /**
     * 扫描线厚度
     */
    var mScanLineDepth =
        TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4f, resources.displayMetrics)

    /**
     * 扫描线每次重绘的移动距离
     */
    var mScanLineDy =
        TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 5f, resources.displayMetrics)

    /**
     * 线性梯度
     */
    var mLinearGradient: LinearGradient? = null

    /**
     * 线性梯度位置
     */
    var mPositions = floatArrayOf(0f, 0.5f, 1f)

    /**
     * 线性梯度各个位置对应的颜色值
     */
    var mScanLineColor = intArrayOf(0x00FFFFFF, Color.WHITE, 0x00FFFFFF)
    override fun onDraw(canvas: Canvas) {
        refreshSizes()
        if (framingRect == null || previewFramingRect == null) {
            return
        }
        val frame: Rect = framingRect
        val previewFrame: Rect = previewFramingRect

        //=====绘制4个角  可以注释此段代码，就像微信那样只要扫描线在动的样式了
        paint.color = mLineColor // 定义四个角画笔的颜色（本身整个扫描界面都为此颜色，通过设置四个角距离而被覆盖，进而形成四个角）
        //左上角
        canvas.drawRect(
            frame.left.toFloat(),
            frame.top.toFloat(),
            frame.left + frame.width() * mLineRate,
            frame.top + mLineDepth,
            paint
        )
        canvas.drawRect(
            frame.left.toFloat(),
            frame.top.toFloat(),
            frame.left + mLineDepth,
            frame.top + frame.height() * mLineRate,
            paint
        )

        //右上角
        canvas.drawRect(
            frame.right - frame.width() * mLineRate,
            frame.top.toFloat(),
            frame.right.toFloat(),
            frame.top + mLineDepth,
            paint
        )
        canvas.drawRect(
            frame.right - mLineDepth,
            frame.top.toFloat(),
            frame.right.toFloat(),
            frame.top + frame.height() * mLineRate,
            paint
        )

        //左下角
        canvas.drawRect(
            frame.left.toFloat(),
            frame.bottom - mLineDepth,
            frame.left + frame.width() * mLineRate,
            frame.bottom.toFloat(),
            paint
        )
        canvas.drawRect(
            frame.left.toFloat(),
            frame.bottom - frame.height() * mLineRate,
            frame.left + mLineDepth,
            frame.bottom.toFloat(),
            paint
        )

        //右下角
        canvas.drawRect(
            frame.right - frame.width() * mLineRate,
            frame.bottom - mLineDepth,
            frame.right.toFloat(),
            frame.bottom.toFloat(),
            paint
        )
        canvas.drawRect(
            frame.right - mLineDepth,
            frame.bottom - frame.height() * mLineRate,
            frame.right.toFloat(),
            frame.bottom.toFloat(),
            paint
        )


        //=======扫描框为的颜色，灰色遮罩层，删除则无灰色遮罩层
        /*
        int width = canvas.getWidth();
        int height = canvas.getHeight();
        paint.setColor(resultBitmap != null ? resultColor : maskColor);//遮罩层的颜色
        canvas.drawRect(0, 0, width, frame.top, paint);
        canvas.drawRect(0, frame.top, frame.left, frame.bottom + 1, paint);
        canvas.drawRect(frame.right + 1, frame.top, width, frame.bottom + 1, paint);
        canvas.drawRect(0, frame.bottom + 1, width, height, paint);
         */if (resultBitmap != null) {
            // Draw the opaque result bitmap over the scanning rectangle
            paint.alpha = CURRENT_POINT_OPACITY
            canvas.drawBitmap(resultBitmap, null, frame, paint)
        } else {

            // ===绘制扫描线
            mScanLinePosition += mScanLineDy.toInt()
            if (mScanLinePosition > frame.height()) {
                mScanLinePosition = 0
            }
            mLinearGradient = LinearGradient(
                frame.left.toFloat(),
                frame.top + mScanLinePosition.toFloat(),
                frame.right.toFloat(),
                frame.top + mScanLinePosition.toFloat(),
                mScanLineColor,
                mPositions,
                Shader.TileMode.CLAMP
            )
            paint.shader = mLinearGradient
            canvas.drawRect(
                frame.left.toFloat(),
                frame.top + mScanLinePosition.toFloat(),
                frame.right.toFloat(),
                frame.top + mScanLinePosition + mScanLineDepth,
                paint
            )
            paint.shader = null
            val scaleX: Float = frame.width() / previewFrame.width().toFloat()
            val scaleY: Float = frame.height() / previewFrame.height().toFloat()
            val frameLeft: Int = frame.left
            val frameTop: Int = frame.top

            /*去掉扫描区域的闪光点
            if (!lastPossibleResultPoints.isEmpty()) {
                paint.setAlpha(CURRENT_POINT_OPACITY / 2);
                paint.setColor(resultPointColor);
                float radius = POINT_SIZE / 2.0f;
                for (final ResultPoint point : lastPossibleResultPoints) {
                    canvas.drawCircle(
                            frameLeft + (int) (point.getX() * scaleX),
                            frameTop + (int) (point.getY() * scaleY),
                            radius, paint
                    );
                }
                lastPossibleResultPoints.clear();
            }
            */

            // draw current possible result points
            if (!possibleResultPoints.isEmpty()) {
                paint.alpha = CURRENT_POINT_OPACITY
                paint.color = resultPointColor
                for (point in possibleResultPoints) {
                    canvas.drawCircle(
                        frameLeft + (point.x * scaleX),
                        frameTop + (point.y * scaleY),
                        POINT_SIZE.toFloat(), paint
                    )
                }

                // swap and clear buffers
                val temp = possibleResultPoints
                possibleResultPoints = lastPossibleResultPoints
                lastPossibleResultPoints = temp
                possibleResultPoints.clear()
            }

            // Request another update at the animation interval, but only repaint the laser line,
            // not the entire viewfinder mask.
            postInvalidateDelayed(
                ANIMATION_DELAY,
                frame.left - POINT_SIZE,
                frame.top - POINT_SIZE,
                frame.right + POINT_SIZE,
                frame.bottom + POINT_SIZE
            )
        }
    }
}